<template>
  <div>
    <Row class="list_row" style="margin-top: 0px">
      <Row style="margin: 5px 0px 10px 0px">
        <Input
          v-model="searchKeyword"
          :placeholder="$t('courseP.planPlacesTips')"
          style="width: 200px; margin-right: 20px"
        />
        <Button
          class="btnWhite"
          type="primary"
          icon="ios-search"
          style="margin-right: 20px"
          @click="search"
          >{{ $t("search") }}</Button
        >
        <Button
          class="btnWhite"
          type="primary"
          icon="md-add"
          @click="showAddModal"
          v-if="roleId == '4'"
          >{{ $t("courseP.addPlanBtn") }}</Button
        >
      </Row>
      <Table
        :columns="planColumn"
        border
        :data="dataList"
        stripe
        :no-data-text="noDataMsg"
      >
        <template slot-scope="{ row, index }" slot="seq">
          {{ (currentPage - 1) * pageSize + index + 1 }}
        </template>
        <template slot-scope="{ row, index }" slot="dateRange">
          {{ row.planStartDate }}~{{ row.planEndDate }}
        </template>
        <template slot-scope="{ row, index }" slot="trainerList">
          <span v-for="user in row.trainerList" style="margin-right: 5px"
            >{{ user.nickName }};</span
          >
        </template>
        <template slot-scope="{ row, index }" slot="courseList">
          <span v-for="course in row.courseList" style="margin-right: 5px"
            >{{ course.name }};</span
          >
        </template>
      </Table>
      <div class="div_page">
        <Page
          :total="totalCount"
          :current="currentPage"
          :page-size="pageSize"
          show-total
          show-elevator
          prev-text="<"
          next-text=">"
          @on-change="pageChg"
        />
      </div>
    </Row>

    <!-- 新增计划分配弹窗 -->
    <Modal
      v-model="entityModelVisiable"
      :mask-closable="false"
      width="900"
      :title="entityModelTitle"
      :styles="{ top: '10px' }"
    >
      <Form
        ref="entityFormRef"
        :model="entityForm"
        :rules="addFormRules"
        :label-width="120"
      >
        <div>
          <Collapse
            v-model="entityForm.courseCollapse"
            accordion
            style="margin-top: 0px"
          >
            <Panel name="base">
              {{ $t("courseP.planInfo") }}
              <div slot="content">
                <Row>
                  <Col span="12">
                    <FormItem :label="$t('courseP.planName')" prop="name">
                      <Input
                        v-model="entityForm.name"
                        :placeholder="$t('courseP.planPlacesTips')"
                        :disabled="entityForm.opeType == 'view'"
                      ></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem
                      :label="$t('courseP.timeSelectLabel')"
                      prop="planStartDate"
                    >
                      <Date-picker
                        v-model="entityForm.planDateScopeArr"
                        format="yyyy-MM-dd"
                        type="daterange"
                        :options="dateRangeOp"
                        placement="bottom-end"
                        @on-change="planDateRangeChange"
                        :placeholder="$t('courseP.timeSelectLabel')"
                        clearable
                        :disabled="entityForm.opeType == 'view'"
                      ></Date-picker>
                    </FormItem>
                  </Col>
                </Row>
                <FormItem :label="$t('courseP.trainTarget')" prop="target">
                  <Input
                    v-model="entityForm.target"
                    type="textarea"
                    :rows="2"
                    :placeholder="$t('courseP.selectTargetG')"
                    :disabled="entityForm.opeType == 'view'"
                  ></Input>
                </FormItem>
                <FormItem
                  :label="$t('courseP.selsectTrainee')"
                  prop="trainerIdList"
                >
                  <Transfer
                    style="margin: 0px 0px"
                    id="userTransfer"
                    :data="allTrainerList"
                    :titles="[
                      this.$t('trainerP.traineeList'),
                      this.$t('courseP.selsectedTrainee'),
                    ]"
                    filterable
                    :list-style="listStyle"
                    :filter-method="filterTrainer"
                    :target-keys="entityForm.trainerIdList"
                    :render-format="transferRender"
                    @on-change="transferOnChange"
                  ></Transfer>
                </FormItem>
              </div>
            </Panel>
            <Panel
              :name="course.uuid"
              v-for="course in entityForm.courseList"
              :key="course.uuid"
            >
              {{ $t("courseP.callocation") }}{{ course.seq }}
              <div style="float: right; margin-right: 20px">
                <Button
                  type="error"
                  size="small"
                  @click.stop="deleteCourse(course.uuid)"
                  v-show="entityForm.opeType != 'view'"
                  >{{ $t("common.deleteBtn") }}
                </Button>
              </div>
              <div slot="content">
                <Row>
                  <Col span="12">
                    <FormItem :label="$t('courseP.sCourse')" prop="planId">
                      <Select
                        v-model="course.id"
                        filterable
                        clearable
                        style="width: 300px"
                        :disabled="entityForm.opeType == 'view'"
                      >
                        <Option
                          v-for="c in allCoachCourseList"
                          :value="c.id"
                          :key="c.id"
                          :disabled="c.disabled"
                          >{{ c.name }}</Option
                        >
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem
                      :label="$t('courseP.trainTime')"
                      prop="trainDateList"
                    >
                      <TimePicker
                        v-model="course.selTrainTimeArr"
                        format="HH:mm"
                        type="timerange"
                        placement="bottom-end"
                        :placeholder="$t('courseP.sTrainTime')"
                        clearable
                        :disabled="entityForm.opeType == 'view'"
                        style="width: 300px; margin-left: 5px"
                      ></TimePicker>
                    </FormItem>
                  </Col>
                </Row>

                <FormItem
                  :label="$t('courseP.sTrainDate')"
                  prop="trainDateList"
                  v-show="entityForm.opeType != 'view'"
                >
                  <Date-picker
                    format="yyyy-MM-dd"
                    type="date"
                    v-model="course.selTrainDate"
                    :options="dateOp"
                    placement="bottom-end"
                    :placeholder="$t('courseP.selectDate')"
                    clearable
                    style="width: 300px"
                  ></Date-picker>
                  <i-button
                    type="info"
                    shape="circle"
                    icon="md-add"
                    @click="addTrainDate(course)"
                    style="margin-left: 10px"
                  ></i-button>
                </FormItem>

                <FormItem
                  :label="$t('courseP.sedTrainDate')"
                  prop="selTrainTime"
                >
                  <Tag
                    v-for="trainDate in course.trainDateList"
                    type="border"
                    closable
                    color="blue"
                    :key="trainDate"
                    @on-close="removeTrainDate(course, trainDate)"
                  >
                    {{ trainDate }}
                  </Tag>
                </FormItem>
              </div>
            </Panel>
          </Collapse>
        </div>

        <Button
          type="warning"
          ghost
          icon="md-add"
          style="width: 100%; margin-top: 15px"
          @click="addCourse()"
          v-show="entityForm.opeType != 'view'"
          >{{ $t("courseP.callocation") }}
        </Button>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable = false">{{ $t("cancel") }}</Button>
        <Button
          type="primary"
          @click="saveOrUpdate"
          :loading="saveLoading"
          style="margin-left: 15px"
          v-show="entityForm.opeType != 'view'"
        >
          <span v-if="!saveLoading">{{ $t("save") }}</span>
          <span v-else>{{ $t("save") }}....</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import CommonApi from "@/api/commonApi";
import PlanApi from "@/api/planApi";
import CourseApi from "@/api/courseApi";
import DayJS from "dayjs";
import { isEmpty, copyObj, genUuid, formatDate } from "@/libs/util";
import { mapGetters } from "vuex";

export default {
  data() {
    const trainerIdListCheck = (rule, value, callback) => {
      if (value.length() == 0) {
        callback(new Error(this.$t("courseP.atlastAneTrain")));
      } else {
        callback();
      }
    };
    const trainTimeIdsChechk = (rule, value, callback) => {
      if (value.length() == 0) {
        callback(new Error(this.$t("courseP.timeZd")));
      } else {
        callback();
      }
    };
    return {
      dateRangeOp: {
        disabledDate(date) {
          return date.valueOf() < Date.now() - 86400000;
        },
      },
      dateOp: {
        disabledDate: (date) => {
          // 要用箭头函数，this才能指向Vm,我指向的是所在位置指向的对象

          if (this.entityForm.planDateScopeArr.length > 0) {
            let tmp1 = this.entityForm.planDateScopeArr[0],
              tmp2 = this.entityForm.planDateScopeArr[1];
            if (DayJS(tmp1).valueOf() < Date.now()) {
              return date < DayJS().subtract(1, "day") || date > new Date(tmp2);
            }
            return date < DayJS(tmp1) || date > new Date(tmp2);
          } else {
            return date.valueOf() < Date.now() - 86400000; // 86400000  一天的秒数
          }
        },
      },
      listStyle: {
        width: "280px",
      },
      collapseStyle: {
        height: "200px",
        overflowY: "auto",
      },
      allCoachCourseList: [],
      allTrainerList: [],
      saveLoading: false,
      searchKeyword: "",
      noDataMsg: this.$t("common.noData"),
      entityModelTitle: this.$t("courseP.addPlan"),
      entityModelVisiable: false,
      entityForm: {
        id: "",
        name: "",
        target: "",
        planStartDate: "",
        planEndDate: "",
        planDateScopeArr: [],
        trainerIdList: [],
        planIdArr: [],
        courseList: [],
        opeType: "add",
        courseCollapse: "",
      },
      addFormRules: {
        name: [
          {
            required: true,
            message: this.$t("courseP.planMust"),
            trigger: "blur",
          },
          {
            type: "string",
            max: 32,
            message: this.$t("courseP.planLow32"),
            trigger: "blur",
          },
        ],
        target: [
          {
            required: true,
            message: this.$t("courseP.trainGMust"),
            trigger: "blur",
          },
          {
            type: "string",
            max: 500,
            message: this.$t("courseP.trainlen500"),
            trigger: "blur",
          },
        ],
        planStartDate: [
          {
            required: true,
            message: this.$t("courseP.periondMust"),
            trigger: "blur",
          },
        ],
        planEndDate: [
          {
            required: true,
            message: this.$t("courseP.periondMust"),
            trigger: "blur",
          },
        ],
      },
      totalCount: 20,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      roleId: "",
      planColumn: [
        {
          title: this.$t("common.seq"),
          slot: "seq",
          width: "110",
          render: (h, params) => {
            return h(
              "span",
              {
                class: "sortBlock",
              },
              params.index + 1
            );
          },
        },
        {
          title: this.$t("courseP.planName"),
          key: "name",
        },
        {
          title: this.$t("common.creator"),
          key: "createUserName",
        },
        {
          title: this.$t("courseP.seDate"),
          slot: "dateRange",
        },
        {
          title: this.$t("common.trainerName"),
          slot: "trainerList",
        },
        {
          title: this.$t("common.courseName"),
          slot: "courseList",
        },
        {
          title: this.$t("common.updateTime"),
          key: "updateTime",
        },
        {
          title: this.$t("common.optColumn"),
          key: "action",
          width: 220,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  class: "btnBlue",
                  on: {
                    click: () => {
                      this.showViewModal(params.row);
                    },
                  },
                },
                this.$t("common.previewBtn")
              ),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small",
                  },
                  class: "btnYellow",
                  style: {
                    marginRight: "15px",
                    display: params.row.canModify ? "inline" : "none",
                  },
                  on: {
                    click: () => {
                      let a = params.row;
                      debugger;
                      this.showEditModal(params.row);
                    },
                  },
                },
                this.$t("common.editBtn")
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  class: "btnRed",
                  style: {
                    display: params.row.canModify ? "inline" : "none",
                  },
                  on: {
                    click: () => {
                      this.del(params.row);
                    },
                  },
                },
                this.$t("common.deleteBtn")
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    this.initCourseList();
    this.initTrainerList();
    this.search();
    this.roleId = this.getRoleId();
    // 计算屏幕高度
    var clientH =
      document.documentElement.clientHeight || document.body.clientHeight;
    clientH = clientH - 220;
    // this.collapseStyle = {
    //   height: clientH + "px",
    //   overflowY: 'auto'
    // }
  },
  watch: {
    entityForm: {
      handler(newVal, oldVal) {
        let allCoachCourseList = this.allCoachCourseList;
       
        if (allCoachCourseList.length > 0) {
          let hasChooseIdArr =[];
          for (let i = 0; i <  newVal.courseList.length; i++) {  
            if(newVal.courseList[i].id){
              hasChooseIdArr.push(newVal.courseList[i].id)
            }
          }
          const uniqueArr = Array.from(new Set(hasChooseIdArr));
          console.log("wwwwwwww",uniqueArr)
          for (let k = 0; k < allCoachCourseList.length; k++) {
            allCoachCourseList[k].disabled = false;
            for(let m=0; m<uniqueArr.length; m++ ){
         
              if (allCoachCourseList[k].id === uniqueArr[m]) {
                allCoachCourseList[k].disabled = true;
              } 
              
            }
            
            }
          console.log("111111", allCoachCourseList);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    ...mapGetters(["getRoleId"]),
    // 初始化教练的学员列表
    initTrainerList() {
      CommonApi.getCoachTrainerList().then(
        (res) => {
          const trainerList = res.data.data.trainerList;
          for (var i = 0; i < trainerList.length; i++) {
            var trainer = trainerList[i];
            trainer["key"] = trainer.id;
          }
          this.allTrainerList = trainerList;
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    // 加载该教练的所有课程
    initCourseList() {
      CourseApi.findUserAllCourseList().then(
        (res) => {
          this.allCoachCourseList = res.data.data;
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    search() {
      this.currentPage = 1;
      this.fetchDataList();
    },
    fetchDataList() {
      this.noDataMsg = this.$t("common.loading");
      this.dataList = [];
      var param = {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        sourceType: 1,
      };
      if (this.searchKeyword.length > 0) {
        param.name = this.searchKeyword;
      }
      PlanApi.pageResult(param).then(
        (res) => {
          this.dataList = res.data.data.pageResult.items;
          this.totalCount = res.data.data.pageResult.totalCount;
          this.noDataMsg = this.$t("common.noData");
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    getDefCourse(seq) {
      seq = seq || 1;
      const course = {
        uuid: genUuid(),
        seq: seq,
        id: "",
        selTrainDate: "",
        trainDateList: [],
        selTrainTimeArr: [],
        trainTime: "",
      };
      return course;
    },
    showAddModal() {
      this.$refs.entityFormRef.resetFields();
      this.entityForm = {
        id: "",
        name: "",
        target: "",
        planStartDate: "",
        planEndDate: "",
        planDateScopeArr: [],
        trainerIdList: [],
        trainDateList: [],
        planIdArr: [],
        opeType: "add",
        courseList: [this.getDefCourse(0)],
        courseCollapse: "",
      };

      // this.entityForm.courseCollapse = this.entityForm.courseList[0].uuid
      this.entityForm.courseCollapse = "base";
      this.entityModelTitle = this.$t("courseP.addPlan");
      this.entityModelVisiable = true;
    },
    planDateRangeChange(formatTimeArr) {
      this.entityForm.planStartDate = formatTimeArr[0];
      this.entityForm.planEndDate = formatTimeArr[1];
    },
    treatPlanInfo(response) {
      var plan = response.data.data.obj;
      for (var i = 0; i < plan.courseList.length; i++) {
        var course = plan.courseList[i];
        course.selTrainTimeArr = course.trainTime.split("~");
      }
      plan.planDateScopeArr = [plan.planStartDate, plan.planEndDate];
      return plan;
    },
    showViewModal(row) {
      this.$refs.entityFormRef.resetFields();
      this.entityModelVisiable = true;
      this.entityModelTitle = this.$t("courseP.viewPlan");
      // this.$Spin.show()
      PlanApi.get(row.id).then(
        (response) => {
          // this.$Spin.hide()
          this.entityForm = this.treatPlanInfo(response);
          // this.entityForm.courseCollapse = this.entityForm.courseList[0].uuid
          this.entityForm.courseCollapse = "base";
          this.entityForm.opeType = "view";

          if (!row.canModify) {
            this.allCoachCourseList = response.data.data.obj.courseList;
            const trainerList = response.data.data.obj.trainerList;
            for (var i = 0; i < trainerList.length; i++) {
              var trainer = trainerList[i];
              trainer["key"] = trainer.id;
            }
            this.allTrainerList = trainerList;
          }
        },
        (error) => {
          this.saveLoading = false;
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    showEditModal(row) {
      this.$refs.entityFormRef.resetFields();
      this.entityModelVisiable = true;
      this.entityModelTitle = this.$t("courseP.editPlan");
      // this.$Spin.show()
      PlanApi.get(row.id).then(
        (response) => {
          // this.$Spin.hide()
          this.entityForm = this.treatPlanInfo(response);
          // this.entityForm.courseCollapse = this.entityForm.courseList[0].uuid
          this.entityForm.courseCollapse = "base";
          if (this.entityForm.executeStatus == 0) {
            this.entityForm.opeType = "edit";
          } else {
            this.$Message.info(this.$t("courseP.noEditPlan"));
            this.entityForm.opeType = "view";
          }
        },
        (error) => {
          this.saveLoading = false;
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    saveOrUpdate() {
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          if (this.entityForm.trainerIdList.length == 0) {
            this.$Message.error(this.$t("courseP.atlastAneTrain"));
            return;
          }
          for (var i = 0; i < this.entityForm.courseList.length; i++) {
            const course = this.entityForm.courseList[i];
            // console.log("进来了： " + JSON.stringify(course))
            if (isEmpty(course.id)) {
              this.$Message.error(
                this.$t("courseP.callocation") +
                  (i + 1) +
                  ":" +
                  this.$t("courseP.psCourse")
              );
              return;
            }
            if (course.trainDateList.length == 0) {
              this.$Message.error(
                this.$t("courseP.callocation") +
                  (i + 1) +
                  ":" +
                  this.$t("courseP.atleastTimeTrain")
              );
              return;
            }
            // console.log("到这里了。。。。")
            if (
              course.selTrainTimeArr == null ||
              course.selTrainTimeArr.length == 0 ||
              course.selTrainTimeArr[0].length == 0
            ) {
              this.$Message.error(
                this.$t("courseP.callocation") +
                  (i + 1) +
                  ":" +
                  this.$t("courseP.timeZd")
              );
              return;
            }
            // console.log("转换时间。。。。")
            // const startTrainTime = formatDate(course.selTrainTimeArr[0], 'HH:MM')
            // const endTrainTime = formatDate(course.selTrainTimeArr[1], 'HH:MM')
            course.trainTime =
              course.selTrainTimeArr[0] + "~" + course.selTrainTimeArr[1];
            // console.log("转换完成")
          }
          // console.log("验证通过")
          this.$Spin.show();
          PlanApi.saveOrUpdate(this.entityForm).then(
            (response) => {
              this.$Spin.hide();
              if (this.entityForm.id == "") {
                this.$Message.success(this.$t("common.addSuc"));
              } else {
                this.$Message.success(this.$t("common.editSuc"));
              }
              this.$refs.entityFormRef.resetFields();
              this.entityModelVisiable = false;
              this.fetchDataList();
            },
            (error) => {
              this.$Spin.hide();
              this.saveLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
        }
      });
    },
    pageChg(selPage) {
      this.currentPage = selPage;
      this.fetchDataList();
    },
    del(row) {
      this.$Modal.confirm({
        title: this.$t("common.dDeleteTitleConfirm"),
        content: this.$t("common.DdeleteCt"),
        okText: this.$t("common.deleteBtn"),
        cancelText: this.$t("cancel"),
        onOk: () => {
          this.doDel(row.id);
        },
      });
    },
    doDel(id) {
      this.$Spin.show();
      PlanApi.delete(id).then(
        (res) => {
          this.$Spin.hide();
          this.$Message.success(this.$t("common.deleteSuc"));
          this.fetchDataList();
        },
        (error) => {
          this.$Spin.hide();
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    filterTrainer(data, query) {
      var name = data.nickName;
      if (isEmpty(name)) {
        name = "";
      }
      return name.indexOf(query) > -1 || data.phone.indexOf(query) > -1;
    },
    transferRender(coach) {
      if (!coach.avatar) {
        if (this.$i18n.locale === "zh-CN") {
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.phone} )</div>`;
        } else {
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.mail} )</div>`;
        }
      } else {
        if (this.$i18n.locale === "zh-CN") {
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.phone} )</div>`;
        } else {
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.mail} )</div>`;
        }
      }
    },
    transferOnChange(newTargetKeys, direction, moveKeys) {
      this.entityForm.trainerIdList = newTargetKeys;
    },
    removeTrainDate(course, trainDate) {
      if (this.entityForm.opeType == "view") {
        return;
      }
      var removeIndex;
      for (var i = 0; i < course.trainDateList.length; i++) {
        if (course.trainDateList[i] == trainDate) {
          removeIndex = i;
          break;
        }
      }
      course.trainDateList.splice(removeIndex, 1);
    },
    addTrainDate(course) {
      if (course.selTrainDate == "") {
        this.$Message.error(this.$t("courseP.sTrainDate"));
        return;
      }
      const formatDateVal = formatDate(course.selTrainDate, "YYYY-mm-dd");
      if (course.trainDateList.includes(formatDateVal)) {
        this.$Message.warning(this.$t("courseP.trainTimeedMsg"));
        return;
      }
      course.trainDateList.push(formatDateVal);
      course.selTrainDate = "";
    },
    addCourse() {
      const courseList = this.entityForm.courseList;
      const course = this.getDefCourse(courseList.length + 1);
      console.log("详情：" + JSON.stringify(course));
      courseList.push(course);
    },
    deleteCourse(uuid) {
      const courseList = this.entityForm.courseList;

      if (courseList.length == 1) {
        this.$Message.error(this.$t("courseP.oneCourseAssign"));
        return;
      }
      var removeIndex;
      for (var i = 0; i < courseList.length; i++) {
        var detail = courseList[i];
        if (detail.uuid == uuid) {
          removeIndex = i;
          break;
        }
      }
      courseList.splice(removeIndex, 1);
      // 重新排序
      for (var i = 0; i < courseList.length; i++) {
        var detail = courseList[i];
        detail.seq = i + 1;
      }
    },
  },
};
</script>
<style lang="less">
.ivu-date-picker {
  width: 100%;
}
.tranBox {
  font-size: 12px;
  display: flex;
  align-items: center;
}
.avatorBox {
  background: url("../../../assets/images/icon_tx_boy.png");
  background-size: contain;
  width: 20px;
  height: 20px;
  margin: 5px;
  margin-left: 0;
}
.ivu-transfer-list-content-item {
  display: flex;
}
</style>
